import json

from tornado.web import RequestHandler

from apps.users.forms import SmsCodeForm
from apps.utils.AsyncYunPian import AsyncYunPian


class SmsHandler(RequestHandler):
    async def post(self, *args, **kwargs):
        param = self.request.body.decode("utf8")
        param = json.loads(param)
        sms_form = SmsCodeForm.from_json(param)

        re_data = {}
        if sms_form.validate():
            yunpian = AsyncYunPian("ec336d122cd721ccfdec0de599d8dd57")
            res = await yunpian.send_single_sms(sms_form.mobile.data,1234)
            if res == True:
                self.set_status(201)
            else:
                self.set_status(400)
                re_data['mobile'] = "短信发送失败"
        else:
            self.set_status(400)
            re_data['mobile'] = sms_form.errors[0]
